package de.wesemann.mediahandbook.le.adapter;

import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import de.wesemann.jdedun.entities.mediahandbook.companies.MediahandbookCompany;
import de.wesemann.mediahandbook.le.R;

/**
 * @author spinner0815
 * 
 */
public class CompanyAdapter extends ArrayAdapter<MediahandbookCompany> {

	// private static final String LOG_TAG =
	// CompanyAdapter.class.getSimpleName();
	private List<MediahandbookCompany> items;
	private final Activity context;

	public CompanyAdapter(Activity context, List<MediahandbookCompany> items) {
		super(context, R.layout.firm_row, items);
		this.context = context;
		this.items = items;
	}

	static class ViewHolder {
		public TextView firmName;
		public TextView firmStreet;
		public TextView firmCity;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.ArrayAdapter#getView(int, android.view.View,
	 * android.view.ViewGroup)
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;

		if (convertView == null) {
			LayoutInflater vi = context.getLayoutInflater();
			convertView = vi.inflate(R.layout.firm_row, null, true);

			holder = new ViewHolder();
			holder.firmName = (TextView) convertView.findViewById(R.id.tv_firmname);
			holder.firmStreet = (TextView) convertView.findViewById(R.id.tv_firm_street);
			holder.firmCity = (TextView) convertView.findViewById(R.id.tv_firm_city);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		MediahandbookCompany comp = items.get(position);
		holder.firmName.setText(comp.getName());
		String houseAdditional = "";
		if (comp.getHousenumber_additional() != null) {
			houseAdditional = comp.getHousenumber_additional();
		}
		holder.firmStreet.setText(comp.getStreet() + " " + comp.getHousenumber() + " " + houseAdditional);

		holder.firmCity.setText(comp.getPostcode() + " " + comp.getCity());
		return convertView;
	}

	@Override
	public int getCount() {
		return items.size();
	}

	@Override
	public MediahandbookCompany getItem(int position) {
		return items.get(position);
	}

	@Override
	public long getItemId(int position) {
		return items.get(position).hashCode();
	}

	public void setItems(List<MediahandbookCompany> companies) {
		notifyDataSetInvalidated();
		this.items = companies;
		notifyDataSetChanged();
	}

	public void addItems(List<MediahandbookCompany> companies) {
		if (companies != null && !(companies.isEmpty())) {
			// this.items.addAll(companies);
			for (MediahandbookCompany comp : companies) {
				add(comp);
			}
			notifyDataSetChanged();
		}

	}
}